﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;

namespace TicTacToe.Core.Persistance
{
    public static class GameManager
    {
        internal static readonly string SaveFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "3DTicTacToe", "saved games");
        private static readonly Collection<SavedGame> SavedGames = new Collection<SavedGame>();

        #region saved games

        static void RefreshSavedGames()
        {
            SavedGames.Clear();

            if (Directory.Exists(SaveFilePath))
                foreach (var f in Directory.GetFiles(SaveFilePath))
                    SavedGames.Add(SavedGame.LoadGame(f));
        }

        public static void DeleteSavedGame(SavedGame savedGame)
        {
            SavedGames.Remove(savedGame);
            File.Delete(savedGame.Filename);
        }

        public static TicTacToeGame LoadGame(SavedGame savedGame)
        {
            return TicTacToeGame.CreateWithTurns(savedGame.Player1, savedGame.Player2,
                                                 savedGame.Turns.OrderBy(n => n.Timestamp));
        }

        public static void SaveGame(TicTacToeGame game)
        {
            SavedGames.Add(SavedGame.SaveGame(game));
        }

        public static IEnumerable<SavedGame> GetAllGames()
        {
            RefreshSavedGames();
            return SavedGames;
        }

        #endregion
    }
}
